use fork::Fork;
use named_sem::NamedSemaphore;
use nix::sys::wait::waitpid;
use nix::unistd::Pid;
use std::error::Error;
use std::process::Command;

fn main() -> Result<(), Box<dyn Error>> {
    let sem_name = "/test_util2";
    // fork process: no chdir, no close stdout/stderr
    match fork::daemon(true, true).expect("fail to fork") {
        Fork::Parent(pid) => {
            eprintln!("[parent] parent process {sem_name}.");
            let mut test_sem = NamedSemaphore::create(sem_name, 0)?;
            test_sem.wait()?;
            let status = waitpid(Pid::from_raw(pid), None)?;
            eprintln!("[parent] child pid {pid} exit status: {status:?}");
        }
        Fork::Child => {
            eprintln!("[child] child process {sem_name}.");
            {
                let mut test_sem2 = NamedSemaphore::create(sem_name, 0)?;
                test_sem2.post()?;
            }
            eprintln!("[child] {sem_name}: child process finish Move().");
            Command::new("/bin/sleep").arg("2").output()?;
        }
    }
    Ok(())
}
